# 北交所录入助审系统 - Docker镜像构建和导出脚本 (PowerShell版本)
# 用于在Windows环境下构建Docker镜像并导出为tar包供离线部署

# 配置变量
$IMAGE_NAME = "bjs-luruzhushen"
$IMAGE_TAG = "latest"
$EXPORT_DIR = "./docker-export"
$EXPORT_FILE = "$EXPORT_DIR/$IMAGE_NAME-$IMAGE_TAG.tar"

Write-Host "========================================" -ForegroundColor Green
Write-Host "北交所录入助审系统 - Docker构建和导出" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green

# 检查Docker是否安装
try {
    docker --version | Out-Null
} catch {
    Write-Host "错误: Docker未安装，请先安装Docker Desktop" -ForegroundColor Red
    exit 1
}

# 检查Docker服务是否运行
try {
    docker info | Out-Null
} catch {
    Write-Host "错误: Docker服务未运行，请启动Docker Desktop" -ForegroundColor Red
    exit 1
}

# 创建导出目录
if (!(Test-Path -Path $EXPORT_DIR)) {
    New-Item -ItemType Directory -Path $EXPORT_DIR | Out-Null
}

# 步骤1: 构建Docker镜像
Write-Host "`n[步骤 1/3] 构建Docker镜像..." -ForegroundColor Yellow
docker build -t "${IMAGE_NAME}:${IMAGE_TAG}" .

if ($LASTEXITCODE -eq 0) {
    Write-Host "✓ Docker镜像构建成功" -ForegroundColor Green
} else {
    Write-Host "✗ Docker镜像构建失败" -ForegroundColor Red
    exit 1
}

# 步骤2: 导出Docker镜像
Write-Host "`n[步骤 2/3] 导出Docker镜像到文件..." -ForegroundColor Yellow
docker save -o $EXPORT_FILE "${IMAGE_NAME}:${IMAGE_TAG}"

if ($LASTEXITCODE -eq 0) {
    Write-Host "✓ Docker镜像导出成功" -ForegroundColor Green
} else {
    Write-Host "✗ Docker镜像导出失败" -ForegroundColor Red
    exit 1
}

# 步骤3: 压缩导出文件（使用7-Zip或系统压缩）
Write-Host "`n[步骤 3/3] 压缩导出文件..." -ForegroundColor Yellow

# 尝试使用Compress-Archive
try {
    Compress-Archive -Path $EXPORT_FILE -DestinationPath "$EXPORT_DIR/$IMAGE_NAME-$IMAGE_TAG.zip" -Force
    Write-Host "✓ 压缩完成" -ForegroundColor Green
    Remove-Item $EXPORT_FILE
    $FINAL_FILE = "$EXPORT_DIR/$IMAGE_NAME-$IMAGE_TAG.zip"
} catch {
    Write-Host "⚠ 压缩失败，但tar文件已生成" -ForegroundColor Yellow
    $FINAL_FILE = $EXPORT_FILE
}

# 显示结果
Write-Host "`n========================================" -ForegroundColor Green
Write-Host "构建和导出完成！" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green

# 显示镜像信息
Write-Host "`n镜像信息:" -ForegroundColor Yellow
docker images "${IMAGE_NAME}:${IMAGE_TAG}"

# 显示导出文件信息
Write-Host "`n导出文件:" -ForegroundColor Yellow
$fileInfo = Get-Item $FINAL_FILE
$fileSizeMB = [math]::Round($fileInfo.Length / 1MB, 2)
Write-Host "  文件: $FINAL_FILE"
Write-Host "  大小: $fileSizeMB MB"

# 显示部署说明
Write-Host "`n离线部署步骤:" -ForegroundColor Yellow
Write-Host "1. 将导出文件传输到目标服务器"
if ($FINAL_FILE -like "*.zip") {
    Write-Host "2. 在目标服务器上解压: Expand-Archive $IMAGE_NAME-$IMAGE_TAG.zip"
    Write-Host "3. 加载镜像: docker load -i $IMAGE_NAME-$IMAGE_TAG.tar"
} else {
    Write-Host "2. 在目标服务器上运行: docker load -i $IMAGE_NAME-$IMAGE_TAG.tar"
}
Write-Host "4. 运行容器: docker run -d -p 8580:8580 --name bjs-luruzhushen ${IMAGE_NAME}:${IMAGE_TAG}"
Write-Host "   或使用docker-compose: docker-compose up -d"

Write-Host "`n全部完成！✨" -ForegroundColor Green

